from flask import jsonify
from werkzeug.exceptions import HTTPException


def register_error_handlers(app):
    # 处理HTTP异常
    @app.errorhandler(HTTPException)
    def handle_http_error(e):
        response = jsonify({
            "error": e.name,
            "message": e.description
        })
        response.status_code = e.code
        return response

    # 处理验证错误
    @app.errorhandler(422)
    @app.errorhandler(400)
    def handle_validation_error(e):
        # 处理Marshmallow验证错误
        if hasattr(e, 'data') and 'messages' in e.data:
            messages = e.data['messages']
            if 'json' in messages:
                return jsonify({
                    "error": "Validation error",
                    "messages": messages['json']
                }), 400
        return jsonify({
            "error": "Bad request",
            "message": "Invalid request data"
        }), 400

    # 处理500错误
    @app.errorhandler(500)
    def handle_internal_error(e):
        app.logger.error(f"Internal error: {str(e)}")
        return jsonify({
            "error": "Internal server error",
            "message": "An unexpected error occurred"
        }), 500

    # 处理404错误
    @app.errorhandler(404)
    def handle_not_found(e):
        return jsonify({
            "error": "Resource not found",
            "message": "The requested resource was not found"
        }), 404

    # 处理405错误
    @app.errorhandler(405)
    def handle_method_not_allowed(e):
        return jsonify({
            "error": "Method not allowed",
            "message": "The HTTP method is not supported for this resource"
        }), 405